<?php

namespace app\admin\logic;


use support\Backend\BackendLogic;
use support\Container;
use support\Exception\ApiException;
use support\Model\ActionLogModel;
use support\Service\LoginService;
use support\Service\UserService;
use Tinywan\Captcha\Captcha;

class LoginLogic extends BackendLogic
{

    protected $username='';
    public function __construct()
    {
        $this->service = Container::get(UserService::class);
    }

    /**
     * 获取验证码
     * @return array
     */
    public function captcha(): array
    {
        $loginService = Container::get(LoginService::class);
        $result = $loginService->captcha();
        return message($result);
    }

    /**
     * 登录
     * @return array
     */
    public function login(): array
    {
        // 请求参数
        $param = request()->post();
        // 登录账号
        $username = trim($param['username'] ?? '');
        if (!$username) throw  new ApiException('登录账号不能为空');
        // 登录密码
        $password = trim($param['password'] ?? '');
        if (!$password) throw  new ApiException('登录密码不能为空');
        // 验证码校验
        $key = trim($param['key'] ?? '');
        // 验证码
        $captcha = trim($param['captcha'] ?? '');
        if (!$key || !$captcha) throw  new ApiException('请输入正确的验证码');
        if (Captcha::check($captcha, $key) === false) {
            throw  new ApiException('请输入正确的验证码');
        }
        $info = $this->service->getInfoByWhere([['username', '=', $username]]);
        if (!$info) throw  new ApiException('登录账号不存在');
        // 使用状态校验
        if ($info['status'] != 1) throw  new ApiException('帐号已被禁用');
        // 密码校验
        $password = get_password($password . $info['salt']);
        if ($password != $info['password']) {
            throw  new ApiException('登录密码不正确');
        }
        $result = \Tinywan\Jwt\JwtToken::generateToken($info);
        $this->username=$info['username'];
        //创建登录日志
        $this->record();
        // 结果返回
        return message($result);
    }

    /**
     * 注销系统
     * @return array
     */
    public function logout(): array
    {

        try {
            $this->username=\Tinywan\Jwt\JwtToken::getUser()['username']??'';
        }catch (\Throwable $e){}
        $this->record(2);
        return message();
    }

    /**
     * 记录日志
     * @param int $type 日志类型  1登录 2登出
     * @return int
     */
    public function record(int $type = 1): int
    {

        $data = [
            'username' =>$this->username,
            'plugin' => request()->plugin,
            'module' => request()->app,
            'controller' => request()->controller,
            'action' => request()->action,
            'method' => request()->method(),
            'url' => request()->path(), // 获取完成URL
            'param' => request()->all() ? json_encode(request()->all()) : '',
            'title' => $type == 1 ? '登录系统' : '退出登录',
            'type' => $type,
            'content' => '',
            'ip' => request()->getRealIp(),
            'user_agent' => request()->header('user-agent') ?: '1',
            'browser'=>get_browse(request()->header()),
            'os'=>get_os(request()->header()),
            'create_time' => time(),
        ];
        return (new ActionLogModel())->insertOne($data);
    }
}
